#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
static int beginnum = 1000;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
typedef struct _ProdInfo
{
        int num;
        struct _ProdInfo *next;
}ProdInfo;
static ProdInfo* head = NULL;
void* thrProducter(void* arg)
{
        //负责在链表添加数据
        while (1){
                ProdInfo* prod = (ProdInfo*)malloc(sizeof(ProdInfo));
                prod->num = beginnum++;
                 printf("%s %lu %d\n", __FUNCTION__,pthread_self(),prod->num);
                //add to list
                pthread_mutex_lock(&mutex);
                prod->next = head;
                head = prod;
                pthread_mutex_unlock(&mutex);
                //发送通知
                pthread_cond_signal(&cond);
                sleep(rand()%2);
        }
        return NULL;
}
void* thrCustomer(void* arg)
{
        ProdInfo *prod = NULL;
        while (1){
                //取出链表的数据
                pthread_mutex_lock(&mutex);
                // if(head == NULL){
                while (head == NULL){ //程序的严谨性要求if改为while
                        pthread_cond_wait(&cond,&mutex);
                }
                prod = head;
                head = head->next;
                printf("%s %lu %d\n", __FUNCTION__,pthread_self(),prod->num);
                free(prod);
                pthread_mutex_unlock(&mutex);
                sleep(rand()%4);
        }        
        return NULL;
}
int main(int argc, char const *argv[])
{
        pthread_t tid[3];
        pthread_create(&tid[0], NULL, thrProducter,NULL);
        pthread_create(&tid[1],NULL,thrCustomer,NULL);
        pthread_create(&tid[2],NULL,thrCustomer,NULL);
        for (int i = 0; i < 3; i++){
                pthread_join(tid[i],NULL);
        }
        pthread_cond_destroy(&cond);
        pthread_mutex_destroy(&mutex);
        pthread_exit(NULL);
        return 0;
}
